﻿using System.Collections.Generic;
using System.IO;

public class RecordInputService : IInputService
{
    public InputOp HandleInput(int inputId)
    {
        List<InputOp> inputOps = _records[inputId];
        int currentTick = Contexts.sharedInstance.game.tick.currentTick;
        if (currentTick >= inputOps.Count)
        {
            return new InputOp();
        }

        InputOp inputOp = inputOps[Contexts.sharedInstance.game.tick.currentTick];
        return inputOp;
    }
    
    private Dictionary<int, List<InputOp>> _records;

    public void Initialize()
    {
        _records = new Dictionary<int, List<InputOp>>();
        StreamReader reader = new StreamReader(Contexts.sharedInstance.game.recordGlobal.recordPath);
        string line = reader.ReadLine();
        List<InputOp> inputOps = null;
        while (line != null)
        {
            if (line.StartsWith("id:"))
            {
                int inputId = int.Parse(line.Substring(3, line.Length - 3));
                inputOps = new List<InputOp>();
                _records.Add(inputId, inputOps);
            }
            else
            {
                int bitOp = int.Parse(line);

                InputOp inputOp = new InputOp();
                inputOps.Add(inputOp);
                inputOp.forward = (bitOp & 0x01) > 0;
                inputOp.left = (bitOp & 0x02) > 0;
                inputOp.back = (bitOp & 0x04) > 0;
                inputOp.right = (bitOp & 0x08) > 0;
                inputOp.buttonA = (bitOp & 0x10) > 0;
                inputOp.buttonB = (bitOp & 0x20) > 0;
            }

            line = reader.ReadLine();
        }

        reader.Close();
    }
}